package oktx.dubbo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import oktx.config.ApplicationContextHolder;

import java.io.IOException;

/**
 * Created by dave on 18-5-19 下午12:51.
 */
public class JsonProcessor {
    private static ObjectMapper mapper;

    public static String toJson(Object o) {
        try {
            return getObjectMapper().writeValueAsString(o);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parse(String json, Class<T> clazz) {
        try {
            return getObjectMapper().readValue(json, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static ObjectMapper getObjectMapper() {
        if (mapper == null) {
            mapper = ApplicationContextHolder.getBean(ObjectMapper.class);
            if (mapper == null) {
                mapper = new ObjectMapper();
            }
        }
        return mapper;
    }
}
